/**
 * @file hcr.c
 * @author      JinChengLong (https://gitee.com/Datejin/)
 * @brief       超声比库函数
 * @version     0.1
 * @date        2023
 * 
 * @copyright   Copyright © 2025 by JinChengLong 
 * 
 * All rights reserved.
 * Unauthorized copying, reproduction, or redistribution of this file via any medium is strictly prohibited.  
 * Proprietary and confidential.
 *   
 */

#include "hcr.h"
#include "Delay.h"

extern uint16_t n;

void time_init(void)
{
	

	RCC_APB2PeriphClockCmd(RCC_APB2Periph_TIM1, ENABLE);			
	TIM_InternalClockConfig(TIM1);		
	
	
	TIM_TimeBaseInitTypeDef TIM_TimeBaseInitStructure;
	TIM_TimeBaseInitStructure.TIM_ClockDivision =TIM_CKD_DIV1;		//TIM2 1分频
	TIM_TimeBaseInitStructure.TIM_CounterMode =TIM_CounterMode_Up;	//向上计数(从零到重装值）
	TIM_TimeBaseInitStructure.TIM_RepetitionCounter =0;				//重复计数器的值（高级定时器）
	TIM_TimeBaseInitStructure.TIM_Prescaler	=72-1;						//PSC预分频器的值(0到65535）72M频率变为100kHz
	TIM_TimeBaseInitStructure.TIM_Period =65536-1	;						//ARR自动重装器的值（周期）（0到65535）
																		//10us计一个数
	TIM_TimeBaseInit(TIM1, &TIM_TimeBaseInitStructure);
	TIM_ClearFlag(TIM1,TIM_FLAG_Update);	
	TIM_ITConfig(TIM1,TIM_IT_Update,ENABLE);		

}






//
/**
 * @brief 超声波初始化
 * 
 */
void HCR04_init(void)
{
	RCC_APB2PeriphClockCmd(GPIOCLK1, ENABLE);			//初始化PA0引脚
		RCC_APB2PeriphClockCmd(GPIOCLK2, ENABLE);			//初始化PA0引脚

	GPIO_InitTypeDef GPIO_InitStructure;
	GPIO_InitStructure.GPIO_Pin=TRIG;
	GPIO_InitStructure.GPIO_Speed=GPIO_Speed_50MHz;
	GPIO_InitStructure.GPIO_Mode=GPIO_Mode_Out_PP;			//复用上拉输入用定时器控制引脚
	GPIO_Init(GPIOPOR1,&GPIO_InitStructure);
	GPIO_InitStructure.GPIO_Pin=ECHO;
	GPIO_InitStructure.GPIO_Speed=GPIO_Speed_50MHz;
	GPIO_InitStructure.GPIO_Mode=GPIO_Mode_IPD;			//复用上拉输入用定时器控制引脚
	GPIO_Init(GPIOPOR2,&GPIO_InitStructure);
	
	GPIO_ResetBits(GPIOPOR1,TRIG);//TRIG
	//GPIO_SetBits(GPIOPOR,ECHO);//ECHO
	time_init();
}


/**
 * @brief 超声波测距
 * 
 * @param i 
 * @return float 返回值:测量距离cm
 */
float  HCR04_m(uint16_t i)
{
	float m=0,m0=0;
	 
	if(i==1)
	{
		GPIO_SetBits(GPIOPOR1,TRIG);//拉高
		Delay_us(20);//大约20us
		GPIO_ResetBits(GPIOPOR1,TRIG);//TRIG//拉低
		
		while(GPIO_ReadInputDataBit(GPIOPOR2,ECHO)==0); //等待高电平到来
		TIM_Cmd(TIM1,ENABLE);						//定时器正常工作
		while(GPIO_ReadInputDataBit(GPIOPOR2,ECHO)==1);//等待高电平结束
		TIM_Cmd(TIM1,DISABLE);//关闭定时器
		n=n+1;
		
		m=TIM_GetCounter(TIM1)*1.0/1000000*170*100;//m*100等于厘米
		TIM1->CNT=0;
		
		Delay_ms(100);
//		
		if(m-m0>=100)
		{
			return m0;
		}
		else if(m-m0<100)
		{
				
		  return m;
		}
		m0=m;
	}
	else if(i!=1)
	{
		TIM_Cmd(TIM1,DISABLE);//关闭定时器
		n=0;
		return 0;
	}
	return 0;
}

